<template>
  <div class="map_container">
    <Header></Header>

    <mapBase class="map" ref="mapBaseRef">
      <template #mapLeft>
        <div class="mapLeft">
          <div class="controler_box">
            <div title="二维/三维切换" @click="toggleMapMode" :class="{ active: is3D }">
              <img src="@/assets/images/2d.png" alt="" v-if="!is3D">
              <img src="@/assets/images/3d.png" alt="" v-else>
            </div>
            <div title="实况" @click="toggleRealtime" :class="{ active: infoData.currentMode === 'realtime' }">
              <img src="@/assets/images/sk.png" alt="">
              <div class="arrow" v-if="infoData.currentMode === 'realtime'"></div>
            </div>
            <div title="历史作业" @click="toggleHistory" :class="{ active: infoData.currentMode === 'history' }">
              <img src="@/assets/images/ls.png" alt="">
              <div class="arrow" v-if="infoData.currentMode === 'history'"></div>
            </div>

            <div title="数据统计" @click="toggleStatistics" :class="{ active: showStatistics }">
              <el-icon color="#5185e8" size="25px">
                <Histogram />
              </el-icon>
            </div>
          </div>

          <!-- 实况查询面板 -->
          <div class="query-panel" v-if="infoData.currentMode === 'realtime'">
            <FlightQueryPanel ref="flightQueryPanelRef" @select-flight="handleSelectFlight"
              @show-drawer="handleShowDrawer" @loading-change="handleLoadingChange" />
          </div>

          <!-- 历史作业面板 -->
          <div class="query-panel" v-if="infoData.currentMode === 'history'">
            <HistoryPanel ref="historyPanelRef" @select-flight="handleSelectFlight" @show-drawer="handleShowDrawer"
              @loading-change="handleLoadingChange" />
          </div>
        </div>
      </template>
    </mapBase>

    <!-- 时间轴组件 -->
    <TimeAxis ref="timeAxisRef" v-if="timeAxis.showTimeAxis" />

    <div class="loading-container" v-if="isTrajectoryLoading">
      <div class="loading-content">
        <div class="loading-spinner">
          <span></span>
        </div>
        <div class="loading-text">轨迹数据加载中...</div>
      </div>
    </div>
    <!-- 右侧抽屉组件 -->
    <InfoDataPanel :flightData="currentFlightData" ref="dmtDataPanelRef" />

    <el-dialog v-model="showStatistics" title="数据统计" width="50%" :before-close="handleClose">
      <div class="statistics-container">
        <div class="query-header">
          <el-select v-model="queryParams.airplaneNo" placeholder="编号" style="width: 240px;margin-right: 10px;">
            <el-option v-for="item in aircraftCodes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="queryParams.source" placeholder="数据源" style="width: 240px ;margin-right: 10px">
            <el-option v-for="item in aircraftType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="queryParams.type" placeholder="类型" style="width: 240px ;margin-right: 10px">
            <el-option v-for="item in typeOption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-date-picker v-model="queryParams.startsFrom" type="date" placeholder="时间" style="margin: 0 10px;"
            value-format="YYYY-MM-DDTHH:mm" format="YYYY-MM-DDTHH:mm" />
          <el-button type="primary" @click="queryStatistics">查询</el-button>
        </div>

        <div class="statistics-content">


          <div class="statistics-chart">
            <div class="chart-container" ref="chartRef"></div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showStatistics = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 飞机编号选择器弹窗 -->
    <el-dialog title="飞机编号选择" v-model="codeDialogVisible" width="500px" :modal="true" :append-to-body="true"
      :close-on-click-modal="false" destroy-on-close class="code-selector-dialog">
      <div class="code-selector">
        <div class="code-manage">
          <el-checkbox v-model="selectAllCodes" label="全选" class="code-checkbox">
          </el-checkbox>
          <el-input v-model="codeSearchText" placeholder="搜索编号" class="code-search" prefix-icon="Search"
            clearable></el-input>
        </div>

        <div class="code-list">
          <el-checkbox-group v-model="queryParams.airplanes" class="code-checkbox-group">
            <div v-for="(code, index) in filteredAircraftCodes" :key="index" class="code-item">
              <el-checkbox :label="code.label" :value="code.value" class="code-checkbox">
              </el-checkbox>
            </div>
          </el-checkbox-group>

          <!-- 空状态 -->
          <div v-if="filteredAircraftCodes.length === 0" class="empty-search">
            <el-icon>
              <Search />
            </el-icon>
            <p>未找到匹配的编号</p>
          </div>
        </div>

        <div class="selection-summary">
          已选择 <span>{{ queryParams.airplanes.length }}</span> /
          {{ aircraftCodes.length }} 个编号
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelCodeSelection">取消</el-button>
          <el-button type="primary" @click="confirmCodeSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import Header from './component/Header/index.vue';
import FlightQueryPanel from './component/FlightQueryPanel/index.vue';
import HistoryPanel from './component/HistoryPanel/index.vue';
import InfoDataPanel from './component/InfoDataPanel/index.vue';
import ChatPanel from './component/ChatPanel/index.vue';
import TimeAxis from '@/components/timeAxis/index.vue';
import { ref, onMounted, onUnmounted, provide, nextTick, computed } from 'vue';
import { getMap } from '@/mapbox/mapbox_core/mapInitialization';
import { clearAllMarkersAndTrails } from '@/mapbox/main/index.js';
import { ElMessage } from 'element-plus';
import drawerStore from "@/stores/modules/drawer";
import { getDictList, realTimeFlights, getStatistic, getHistoryProbe, getHistoryMessage } from "@/api/aircraft";
import *as echarts from 'echarts';
import timeAxisStore from "@/stores/modules/timeAxis";
import useInfoDataStore from "@/stores/modules/infoData";


const infoData = useInfoDataStore();

const timeAxis = timeAxisStore()

const drawer = drawerStore();
const mapBaseRef = ref(null);
const is3D = ref(false);
const timeAxisRef = ref(null);

provide('timeAxisRef', timeAxisRef);

// 轨迹数据加载状态
const isTrajectoryLoading = ref(false);



// 定时器
let realtimeTimer = null;
let historyTimer = null;
const dmtDataPanelRef = ref(null);

// 当前选中的航班数据
const currentFlightData = ref(null);

const flightQueryPanelRef = ref(null);
const historyPanelRef = ref(null);
const chatPanelRef = ref(null);
const showChat = ref(false);

const handleLoadingChange = (loading) => {
  if (loading) {
    isTrajectoryLoading.value = true;
  } else {
    setTimeout(() => {
      isTrajectoryLoading.value = false;
    }, 300);
  }
};

onMounted(() => {
  getDictListData();
})

const aircraftCodes = ref([]);
const aircraftType = ref([]);
const queryParams = ref({
  airplaneNo:
    "B650N",
  source:
    "XIFEI",
  type:
    "TRACK",
  startsFrom:
    "2025-05-19T00:00"
});
const typeOption = ref([]);
const codeDialogVisible = ref(false);

// 获取字典数据
const getDictListData = async () => {
  try {
    const res = await getDictList();
    aircraftCodes.value = res.find((item) => item.type === "AIRPLANE").elements;
    aircraftType.value = res.find((item) => item.type === "SOURCE").elements;
    typeOption.value = res.find((item) => item.type === "TYPE").elements;
    // queryParams.value.sources = aircraftType.value.map((item) => item.value);
    // queryParams.value.airplanes = aircraftCodes.value.map((item) => item.value);
    // realTimeFlightsData(); 
  } catch (error) {
    console.error(error);
  }
};



// 打开编号选择器
const openCodeSelector = () => {
  codeDialogVisible.value = true;
};

// 打开抽屉方法
const openDrawer = (data) => {
  if (!data) {
    return;
  }


  // 更新当前航班数据
  currentFlightData.value = data;
};

// 处理选择飞机事件
const handleSelectFlight = (flight) => {
  if (!flight) return;
  getMsgData()

  // 更新当前航班数据
  currentFlightData.value = flight;
  if (infoData.currentMode === 'realtime') {
    showRealtimeFlight(flight);
  } else if (infoData.currentMode) {
    showHistoryFlight(flight);
  }
};

// 处理显示抽屉数据事件
const handleShowDrawer = () => {
  // 如果抽屉未打开，确保打开抽屉
  if (!drawer.showDrawer) {
    drawer.toggleDrawer();
  }
};


// 显示实况飞机
const showRealtimeFlight = (flight) => {
  if (infoData.currentMode === 'history') {
    clearHistoryFlight();
  }
  // state.currentMode = 'realtime';
  infoData.currentMode = 'realtime';

  dmtDataPanelRef.value?.updateFlightData(flight);
};





// 显示历史飞机
const showHistoryFlight = (flight) => {

  if (infoData.currentMode === 'realtime') {
    clearRealtimeFlight();
  } 


  infoData.currentMode = 'history';

  if (!drawer.showDrawer) {
    drawer.toggleDrawer();
  }
  dmtDataPanelRef.value?.updateFlightData(flight);
};

// 清除实况飞机显示
const clearRealtimeFlight = () => {

  if (infoData.currentMode === 'realtime') {
    clearInterval(realtimeTimer);
    const map = getMap();
    if (map) {
      clearAllMarkersAndTrails(map);
    }
  }
};

// 清除历史飞机显示
const clearHistoryFlight = () => {
  if (infoData.currentMode === 'history') {
    clearInterval(historyTimer);
  }
};

const toggleMapMode = () => {
  is3D.value = !is3D.value;
  const map = getMap();
  if (map) {
    if (is3D.value) {
      map.setProjection('globe');
      map.setPitch(60);
    } else {
      map.setProjection('mercator');
      map.setPitch(0);
    }
  }
};

const toggleRealtime = () => {
  if (infoData.currentMode === 'realtime') {
    infoData.currentMode = ""
    return
  }
  infoData.currentMode = 'realtime';
  timeAxis.setShowTimeAxis(false)
};

const toggleHistory = () => {
  if (infoData.currentMode === 'history') {
    infoData.currentMode = null
  timeAxis.setShowTimeAxis(false)

    return
  }
  timeAxis.setShowTimeAxis(true)
  infoData.currentMode = 'history';
  timeAxis.setShowTimeAxis(infoData.currentMode)
};

const showStatistics = ref(false);

const chartRef = ref(null);

let eventSources = null
const getMsgData = () => {
  eventSources = new EventSource(
    `${import.meta.env.VITE_WEB_BASE_API}/message/realtime/sse?fn=${currentFlightData.value}`
  );
  eventSources.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log(data);
  }
}


// 更新图表
const updateChart = (echartData) => {
  if (!chartRef.value) return;

  let chart = echarts.init(chartRef.value);
  if (echartData.length === 0) {
    chart.setOption({
      series: [],
    })
  }


  let bgColor = "#fff";
  let color = ["#0090FF", "#36CE9E"];
  let xAxisData = echartData.map((v) => v.axis);
  let yAxisData1 = echartData.map((v) => v.cnt);
  let yAxisData2 = echartData.map((v) => v.invalid);
  const hexToRgba = (hex, opacity) => {
    let rgbaColor = "";
    let reg = /^#[\da-f]{6}$/i;
    if (reg.test(hex)) {
      rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
        "0x" + hex.slice(3, 5)
      )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
    }
    return rgbaColor;
  };

  let option = {
    backgroundColor: bgColor,
    color: color,
    legend: {
      right: 30,
      top: 20,
      textStyle: {
        color: '#666',
        fontSize: 12
      },
    },
    tooltip: {
      trigger: "axis",
      // formatter: function (params) {


      //   return html;
      // },
      extraCssText:
        "background: #fff; border-radius: 0;box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);color: #333;",
      axisPointer: {
        type: "shadow",
        shadowStyle: {
          color: "#ffffff",
          shadowColor: "rgba(225,225,225,1)",
          shadowBlur: 5,
        },
      },
    },
    grid: {
      top: "20%",
      left: "5%",
      right: "5%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        axisLabel: {
          textStyle: {
            color: "#333",
          },
        },
        axisLine: {
          lineStyle: {
            color: "#D9D9D9",
          },
        },
        data: xAxisData,

      },
    ],
    yAxis: [
      {
        type: "value",
        name: "个数",
        axisLabel: {
          textStyle: {
            color: "#666",
          },
        },
        nameTextStyle: {
          color: "#666",
          fontSize: 12,
          lineHeight: 40,
        },
        splitLine: {
          lineStyle: {
            type: "dashed",
            color: "#E9E9E9",
          },
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: "总个数",
        type: "line",
        smooth: true,
        // showSymbol: false,
        // symbolSize: 8,
        // zlevel: 3,
        lineStyle: {
          normal: {
            color: color[0],
            shadowBlur: 3,
            shadowColor: hexToRgba(color[0], 0.5),
            shadowOffsetY: 8,
          },
        },
        areaStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0,
                  color: hexToRgba(color[0], 0.3),
                },
                {
                  offset: 1,
                  color: hexToRgba(color[0], 0.1),
                },
              ],
              false
            ),
            shadowColor: hexToRgba(color[0], 0.1),
            shadowBlur: 10,
          },
        },
        data: yAxisData1,
      },
      {
        name: "无效个数",
        type: "line",
        smooth: true,
        // showSymbol: false,
        // symbolSize: 8,
        zlevel: 3,
        lineStyle: {
          normal: {
            color: color[1],
            shadowBlur: 3,
            shadowColor: hexToRgba(color[1], 0.5),
            shadowOffsetY: 8,
          },
        },
        areaStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0,
                  color: hexToRgba(color[1], 0.3),
                },
                {
                  offset: 1,
                  color: hexToRgba(color[1], 0.1),
                },
              ],
              false
            ),
            shadowColor: hexToRgba(color[1], 0.1),
            shadowBlur: 10,
          },
        },
        data: yAxisData2,
      },
    ],
    dataZoom: {

      realtime: true,
      start: 0,
      end: 100,
      bottom: 10,
      height: 25,
      fillerColor: 'rgba(64, 158, 255, 0.15)',
      textStyle: {
        color: '#666',
        size: 12
      },
    }
  };
  chart.setOption(option);


}

// 执行查询
const queryStatistics = async () => {
  let result = await getStatistic(queryParams.value);
  updateChart(result);
};

// 关闭弹窗
const handleClose = () => {
  showStatistics.value = false;
};

const toggleStatistics = () => {
  showStatistics.value = true;
  updateChart([]);
}

const toggleNews = () => {
  showChat.value = !showChat.value;
};

// 组件卸载时清理定时器和EventSource
onUnmounted(() => {
  clearInterval(realtimeTimer);
  clearInterval(historyTimer);
});

</script>

<style lang="scss" scoped>
.map_container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.mapLeft {
  padding: 16px 8px 8px 8px;
  display: flex;
  flex-direction: row;
  align-items: flex-start;

  .controler_box {
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 12px;
    background-color: rgba(255, 255, 255, 0.95);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
    z-index: 10;
    padding: 5px;
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
    border: 1px solid rgba(255, 255, 255, 0.3);

    div {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      border-radius: 8px;
      transition: all 0.3s;
      position: relative;
      margin: 3px 0;

      &:hover {
        background-color: rgba(230, 230, 230, 0.6);
        transform: translateY(-2px);
      }

      &.active {
        background-color: #ecf5ff;
        box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
      }

      .arrow {
        position: absolute;
        right: -12px;
        top: 50%;
        transform: translateY(-50%);
        width: 0;
        height: 0;
        border-top: 6px solid transparent;
        border-bottom: 6px solid transparent;
        border-left: 8px solid #ecf5ff;
        filter: drop-shadow(2px 0 2px rgba(0, 0, 0, 0.1));
      }

      img {
        width: 24px;
        height: 24px;
        object-fit: contain;
        transition: all 0.3s;
      }

      &:hover img {
        transform: scale(1.1);
      }

      &:active img {
        transform: scale(0.95);
      }
    }

    &::before {
      content: '';
      position: absolute;
      top: -6px;
      left: -6px;
      right: -6px;
      bottom: -6px;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.01) 100%);
      border-radius: 18px;
      z-index: -1;
      opacity: 0.5;
      pointer-events: none;
    }
  }

  .query-panel {
    width: 340px;
    margin-left: 14px;
    border-radius: 12px;
    overflow: hidden;
    z-index: 5;
    background-color: rgba(244, 248, 255, 0.9);
    border: 1px solid #cfe1ff;
    animation: slideIn 0.3s ease-out forwards;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);

    @keyframes slideIn {
      from {
        opacity: 0;
        transform: translateX(-20px);
      }

      to {
        opacity: 1;
        transform: translateX(0);
      }
    }
  }
}

.mapLeftBottom {

  .news {
    border-radius: 40%;
    padding: 0 5px !important;
    box-sizing: border-box;
  }

}



.drawer-content-wrapper {
  padding: 10px;
  height: 100%;
  box-sizing: border-box;

  .flight-detail,
  .weather-info {
    min-height: 200px;
  }
}


.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.loading-spinner {
  display: flex;
  gap: 8px;

  &::before,
  &::after,
  & span {
    content: '';
    width: 8px;
    height: 8px;
    display: block;
    background-color: #409EFF;
    border-radius: 50%;
    animation: bounce 0.5s ease-in-out infinite;
  }

  &::before {
    animation-delay: -0.3s;
  }

  & span {
    animation-delay: -0.15s;
  }
}

.loading-text {
  color: #409EFF;
  font-size: 14px;
  font-weight: normal;
}

@keyframes bounce {

  0%,
  100% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-10px);
  }
}

/* 数据统计弹窗样式 */
.statistics-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.query-header {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.statistics-content {
  display: flex;
  height: 400px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.statistics-tabs {
  width: 150px;
  background-color: #f5f7fa;
  border-right: 1px solid #ebeef5;
}

.tab-item {
  padding: 15px 10px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.tab-item:hover {
  background-color: #ecf5ff;
}

.tab-item.active {
  background-color: #ecf5ff;
  color: #409EFF;
  border-left: 3px solid #409EFF;
  font-weight: 500;
}

.statistics-chart {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-container {
  width: 100%;
  height: 100%;
}

.flight-selector {
  max-height: 300px;
  overflow-y: auto;
}

.flight-selector .el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 8px;
  font-size: 14px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;

  .section-label {
    min-width: 70px;
    font-weight: 500;
  }

  .checkbox-group {
    flex: 1;
    overflow: auto;

    .custom-checkbox-group {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .custom-checkbox {
        margin-right: 0 !important;
        border-radius: 4px;
        padding: 2px;
        box-sizing: border-box;

        :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
          color: #409eff;
        }

        :deep(.el-checkbox__label) {
          font-size: 12px;
          padding-left: 6px;
        }

        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
          background-color: #409eff;
          border-color: #409eff;
        }
      }
    }
  }

  &.flight-path-title {
    margin-bottom: 10px;
  }

  &.aircraft-code-title {
    margin-bottom: 10px;

    .filter-action {
      flex: 1;

      .selected-codes {
        display: inline-flex;
        align-items: center;
        color: #409eff;
        cursor: pointer;
        font-size: 13px;
        background-color: #f0f7ff;
        padding: 4px 10px;
        border-radius: 4px;
        max-width: 200px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        transition: all 0.2s;
        border: 1px solid #e0efff;

        &:hover {
          background-color: #e0efff;
          border-color: #c6e2ff;
        }

        .filter-icon {
          margin-left: 6px;
          font-size: 12px;
        }
      }

      .selection-counts {
        margin-top: 4px;
        margin-left: 2px;
        font-size: 12px;
        color: #606266;

        span {
          color: #409eff;
          font-weight: 500;
        }
      }
    }
  }

  &.flight-list-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: none;
    margin-bottom: 6px;
    padding-bottom: 0;

    .add-flight-btn {
      font-size: 12px;
      padding: 4px 8px;
      height: 28px;

      .el-icon {
        margin-right: 2px;
      }
    }
  }
}
</style>